const express = require('express');
const fileUploader = require('express-fileupload');
const bodyParser = require('body-parser');
const {
  resolve,
  extname
} = require('path')
const {
  appendFileSync,
  existsSync,
  writeFileSync
} = require('fs');

const ALLOWED_TYPE = {
  'video/mp4': 'mp4',
  'video/ogg': 'ogg'
}

const PORT = 7216;

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }))
app.use(fileUploader());
app.use('/upload', express.static(resolve(__dirname, './upload')))

app.all('*', (req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, UPDATE');
  next();
}) 

app.post('/upload', (req, res) => {
  console.log('===================')
  console.log(req.body, req.files)
  console.log('===================')

  const {
    name,
    size,
    type,
    fileName,
    uploadedSize
  } = req.body;

  const {file} = req.files;

  // 文件中途丢失
  if (!file) {
    res.send({
      msg: 'NO file uploaded',
      code: 1001
    })
    return;
  }

  // 文件类型不符合
  if (!ALLOWED_TYPE[type]) {
    res.send({
      msg: ''
    })
  }

  const filename = fileName + extname(name);
  const filePath = resolve(__dirname, './upload/video/' + filename);

  if (uploadedSize !== '0') {
    if (!existsSync(filePath)) {
      res.send({
        code: 1003,
        msg: 'No file exists'
      })
      return;
    }

    appendFileSync(filePath, file.data);

    res.send({
      code: 0,
      msg: 'Appended',
      file_url: 'http://localhost:7216/upload/video/' + filename
    })

    return;
  }

  writeFileSync(filePath, file.data);
  
  res.send({
    code: 0,
    msg: 'File is created'
  })
})

app.listen(PORT, () => {
  console.log(`App is listening on port ${PORT}!`)
})

